import React from 'react'
import App from 'next/app'
import { Provider } from 'react-redux'
import withRedux  from 'next-redux-wrapper'
import { Router } from 'next/router'
import 'antd/dist/antd.css'
import Layout from '../components/Layout'
import PageLoading from '../components/PageLoading'
import makeStore from '../store/store'
class MyApp extends App {
  static async getInitialProps({Component, ctx}) {
    return {
      pageProps: {
        ...(Component.getInitialProps ? await Component.getInitialProps(ctx) : {}),
      }
    };
  }
  state = {
    loading: false
  }
  startLoading = () => {
    this.setState({
      loading: true
    })
  }
  
  stopLoading = () => {
    this.setState({
      loading: false
    })
  }
  
  componentDidMount () {
    Router.events.on('routeChangeStart', this.startLoading)
    Router.events.on('routeChangeComplete',this.stopLoading)
    Router.events.on('routeChangeError', this.stopLoading)
    //axios.get('https://api.github.com/search/repositories?q=react').then(res => console.log(res))
  }
  componentWillUnmount() {
    Router.events.off('routerChangeStart', this.startLoading)
    Router.events.off('routerChangeComplete',this.stopLoading)
    Router.events.off('routerChangeError', this.stopLoading)
  }
  
  
  render() {
    //Component是page下的组件
    //pageProps是组件属性
    const {Component, pageProps, store} = this.props
    return (
      <Provider store={store}>
        <Layout>
          { this.state.loading ? <PageLoading/> : null}
          <Component {...pageProps} />
        </Layout>
      </Provider>
    )
  }
}
export default withRedux(makeStore)(MyApp);


